<template>
  <Modal
    ref="modal"
    title="修改价格"
    width="400px"
  >
    <template #reference>
      <slot />
    </template>
    <el-form
      ref="form"
      label-width="80px"
      :model="form"
      :rules="rules"
    >
      <el-form-item
        label="企业名称"
        prop="companyName"
      >
        <el-input
          v-model.trim="form.companyName"
          disabled
        />
      </el-form-item>
      <el-form-item
        label="原价"
        prop="oldPrice"
      >
        <el-input
          :value="convertYuan2Fen(value.payPrice)"
          disabled
        />
      </el-form-item>
      <el-form-item
        label="现价"
        prop="payPrice"
      >
        <el-input v-model.trim="form.payPrice" />
      </el-form-item>
    </el-form>
    <span class="text-red-500 ml-8">* 价格一经修改不可撤销，请谨慎操作</span>
    <template #footer>
      <div class="text-center">
        <el-button @click="() => $refs.modal.hide()">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="handleSave"
        >
          确定
        </el-button>
      </div>
    </template>
  </Modal>
</template>

<script>
import { assign, pick } from 'lodash-es'
import { changePrice } from '@/api/order'
import { isSuccess } from '@/utils/common'

export default {
    components: {
        Modal: () => import('@/components/Modal'),
    },
    props: {
        value: {
            type: Object,
            default() {
                return {}
            },
        },
    },
    data() {
        return {
            form: {},
            rules: {
                payPrice: [
                    { required: true, message: '必填' },
                    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/,message: '最多输入两位小数', trigger: 'blur' },
                ],
            },
        }
    },
    watch: {
        value: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.form = assign({}, this.form, val)
                    this.form.payPrice = this.convertYuan2Fen(val.payPrice)
                }
            },
        },
    },
    methods: {
        async handleSave() {
            const valid = await this.$refs.form.validate()
            if (valid) {
                const res = await changePrice(pick(this.form, ['id', 'payPrice']))
                if (isSuccess(res)) {
                    this.$message.success('价格修改成功！')
                    this.$refs.modal?.hide()
                    this.$store.dispatch('order/list')
                }
            }
        },
    },
}
</script>